package example.simple;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Calendar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;

public class Test {
	private static Log log = LogFactory.getLog(Test.class);
	public static void main(String[]args) throws Exception {
		testMarshal();
		testUnmarshal();
	}
	private static void testMarshal() throws MarshalException, ValidationException {
		log.info("Begin testMarshal ...");
		
		User user = new User();
		user.setName("kongxx");
		user.setSex(1);
		user.setBirthday(Calendar.getInstance().getTime());

		StringWriter writer = new StringWriter();

		Marshaller.marshal(user, writer);
		
		log.info(writer.getBuffer().toString());
		
		log.info("End testMarshal ...");
	}
	
	private static void testUnmarshal() throws MarshalException, ValidationException {
		log.info("Begin testUnmarshal ...");
		
		StringBuffer sb;
		StringReader reader;
		User user;
		
		log.info("Use element as property of bean");
		
		sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		sb.append("<user><name>kongxx</name><sex>1</sex><birthday>3855-09-15T00:00:00.000+08:00</birthday></user>");

		reader = new StringReader(sb.toString());
		user = (User) Unmarshaller.unmarshal(User.class, reader);
		
		log.info("name:" + user.getName());
		log.info("sex:" + user.getSex());
		log.info("birthday:" + user.getBirthday());
		
		log.info("Use attribute as property of bean");
		sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		sb.append("<user name=\"kongxx\" sex=\"1\" birthday=\"3855-09-15T00:00:00.000+08:00\"></user>");

		reader = new StringReader(sb.toString());
		user = (User) Unmarshaller.unmarshal(User.class, reader);
		
		log.info("name:" + user.getName());
		log.info("sex:" + user.getSex());
		log.info("birthday:" + user.getBirthday());
		
		log.info("End testUnmarshal ...");
	}
}
